const Department = require('../models/department');
const ObjectId = require('mongodb').ObjectId
const User = require('../models/user');


const getAllDepartments = async (req, res) => {
  try {
    const departments = await Department.find()
      .select('_id name createdAt updatedAt children departmentCreater departmentDescription departmentEmail departmentPhoneNumber')
      .populate({
        path: 'children',
        select: '_id name createdAt updatedAt departmentCreater departmentDescription departmentEmail departmentPhoneNumber',
      });
    res.json(departments);
  } catch (error) {
    throw new Error('获取错误: ', error);
  }
};



// 定义一个方法，根据参数查询部门数据和用户数据
const getDepartmentAndUsers = async (req,res) => {
  const {id1 , id2} = req.body
  let departmentUsers = []
  try {
    let department;

    // 如果传入了两个参数，则先查询第一个参数对应的部门文档
    if (id2) {
        department = await Department.findById(id1)

        department = department.children.find(child => child._id == id2)

    
        departmentUsers = department.users
    } else {
      // 如果只传入了一个参数，则只查询第一层中的部门文档
       department = await Department.findById(id1)
       
       departmentUsers = department.users
    }

    const userIds = departmentUsers.map((userObj) => userObj.user);
    console.log(userIds);

    // 查询 User 表中与 userIds 匹配的对象
    const users = await User.find({
      _id: {
        $in: userIds,
      },
    }).select('_id personalSignature account role department createdAt updatedAt avatar email nickname phone');

    // 返回匹配的用户对象
    res.status(200).json({
      departmentUsers: users,
    });

       
  } catch (error) {
    console.error(error);
    throw new Error('Failed to get department and users');
  }
};
const addDepartment = async (req, res) => {
    const { name,departmentCreater,departmentEmail,departmentPhoneNumber,departmentDescription} = req.body;

    try {
      const newDepartment = new Department({
        name,departmentCreater,departmentEmail,departmentPhoneNumber,departmentDescription
      });

      const savedDepartment = await newDepartment.save();

      res.status(201).json(savedDepartment);
    } catch (error) {
      console.error(error);
      res.status(500).json({ message: 'Internal server error' });
    }
};


const setJobTitle = async(req,res) => {
    const { userId, jobTitle } = req.body;
    const _id = new ObjectId(req.user.userId)
    const currentUser = req.user; // 当前登录用户
    if (currentUser.role !== 'admin') {
        return res.status(403).json({ message: 'Forbidden' });
    }
    try {
        const user = await User.findByIdAndUpdate(
        userId,
        { jobTitle },
        { new: true }
        );
        if (!user) {
        return res.status(404).json({ message: 'User not found' });
        }
        res.json({ user });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
}

const updateDepartmentInfo = async (req, res) => {
  const {
    name,
    departmentCreater,
    departmentEmail,
    departmentPhoneNumber,
    departmentDescription
  } = req.body;

  try {
    const department = await Department.findByIdAndUpdate(
      req.params.departmentId,
      {
        name,
        departmentCreater,
        departmentEmail,
        departmentPhoneNumber,
        departmentDescription
      },
      { new: true } // 返回更新后的文档
    );
    res.status(200).send(department);
  } catch (error) {
    console.error(error);
    res.status(500).send('Internal Server Error');
  }
}

const createChildDepartment = async (req, res) => {
  const { name,departmentCreater,departmentEmail,departmentPhoneNumber,departmentDescription} = req.body;
    try {
      // 1. 找到要添加子部门的父级部门
      const parentDepartment = await Department.findById(req.params.parentId);
        console.log(parentDepartment)
      // 2. 如果找不到父级部门，返回错误
      if (!parentDepartment) {
        return res.status(404).json({ error: '父级部门不存在' });
      }
  
      // 3. 创建新的子部门
      const childDepartment = new Department({
        name, departmentCreater, departmentEmail, departmentPhoneNumber, departmentDescription
      });
      
      // 保存子部门
      
      
      // 更新父级部门的 children 数组
      await Department.findOneAndUpdate(
        { _id: parentDepartment._id },
        { $push: { children: childDepartment} },
        { new: true }
      );
      
      // 保存父级部门
      await parentDepartment.save();
  
      // 7. 返回新创建的子部门
      res.status(201).json(childDepartment);
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: '服务器内部错误' });
    }
  };
  

module.exports = {
  getAllDepartments,
  addDepartment,
  createChildDepartment,
  updateDepartmentInfo,
  getDepartmentAndUsers
};
